package com.cqw.service;

import com.alibaba.fastjson.JSON;
import com.cqw.common.PageableEntitiesConverter;
import com.cqw.constant.RedisKeyConstant;
import com.cqw.domain.Activity;
import com.cqw.enums.ActivityStatusEnum;
import com.cqw.exception.CommonException;
import com.cqw.mapper.one.ActivityMapper;
import com.cqw.utils.StringUtils;
import com.cqw.vo.ActivityVO;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-04-28 14:02
 * @Description: ${Description}
 */
@Service
@Slf4j
public class ActivityService {


    @Resource
    private ActivityMapper activityMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 分页查询活动
     *
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public List<Activity> getActivityList(Integer pageIndex, Integer pageSize) {
        PageHelper.startPage(pageIndex, pageSize, "create_time desc");
        List<Activity> list = activityMapper.selectActivityList();
        return PageableEntitiesConverter.toPageEntities(list);
    }

    /**
     * 新建活动
     *
     * @param activityVO
     */
    @Transactional(rollbackFor = Throwable.class)
    public Activity createActivity(ActivityVO activityVO) {
        Activity activity = new Activity(activityVO);
        activityMapper.insert(activity);
        check();
        return activity;
    }

    private void check() {

        List<Activity> activityList = activityMapper.selectActivityList();
        System.out.println(activityList);
    }


    /**
     * 修改活动
     *
     * @param activityVO
     */
    public void updateActivity(ActivityVO activityVO) {
        Activity activityInfo = getActivityInfo(activityVO.getId(), false);
        if (activityInfo == null) {
            throw new CommonException("活动不存在");
        }
        Activity activity = new Activity(activityVO);
        activityMapper.updateByPrimaryKeySelective(activity);
        getActivityInfo(activityVO.getId(), true);
    }


    /**
     * 发布活动
     *
     * @param activityId
     */
    public void publishActivity(Long activityId) {
        Activity activityInfo = getActivityInfo(activityId, false);
        if (activityInfo == null) {
            throw new CommonException("活动不存在");
        }
        changeActivityStatus(activityId, ActivityStatusEnum.pushing.getCode());
    }


    /**
     * 修改活动状态
     *
     * @param activityId
     * @param status
     */
    public void changeActivityStatus(Long activityId, Integer status) {
        Activity activity = new Activity();
        activity.setId(activityId);
        activity.setStatus(status);
        activityMapper.updateByPrimaryKeySelective(activity);
        getActivityInfo(activityId, true);
    }

    /**
     * 获取活动信息
     *
     * @param activityId
     * @param refresh
     * @return
     */
    public Activity getActivityInfo(Long activityId, boolean refresh) {
        String key = RedisKeyConstant.ACTIVITY + activityId;
        Activity activity;
        activity = (Activity) redisTemplate.opsForValue().get(key);
        if (StringUtils.isNull(activity) || refresh) {
            //从数据库查
            activity = activityMapper.selectByPrimaryKey(activityId);
            if (StringUtils.isNull(activity)) {
                return null;
            }
            redisTemplate.opsForValue().set(key, activity, 1, TimeUnit.MINUTES);
        }
        log.info("活动信息：{}", JSON.toJSONString(activity));
        return activity;
    }


    /**
     * 定时将已发布活动修改成进行中
     */
    public void autoActivityStart() {
        //查询已发布，活动已开始的活动
        List<Activity> activityList = activityMapper.selectAutoActivityStart();
        if (CollectionUtils.isNotEmpty(activityList)) {
            for (Activity activity : activityList) {
                log.info("定时将已发布活动修改成进行中activityId：{}", activity.getId());
                changeActivityStatus(activity.getId(), ActivityStatusEnum.starting.getCode());
            }
        }
    }


    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void log() {
        Activity activity = new Activity();
        activity.setActivityName("测试回滚");
        activity.setActivityUrl("");
        activity.setStartTime(new Date());
        activity.setEndTime(new Date());
        activity.setType(1);
        activity.setStatus(1);
        activity.setRemark("备注");
        activity.setCreateTime(new Date());
        activity.setCreateBy(1L);
        activity.setUpdateTime(new Date());
        activity.setUpdateBy(1L);
        activityMapper.insert(activity);
    }
}
